import axios from 'axios'
// import dayjs from 'dayjs'
// import qs from 'qs'
import Message from 'vue-m-message'
import { ElMessage } from 'element-plus'
import useSettingsStore from '@/store/modules/settings'
import axiosAPI from '@/store/modules/AxiosAPI'
import useUserStore from '@/store/modules/user'
import storage from '@/utils/storage'

const api = axios.create({
  baseURL: (import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true') ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 3000 * 60,
  responseType: 'json',
})

const AxiosApi = axiosAPI()

let pollingNum = storage.local.get('pollingNum') ?? 0

api.interceptors.request.use(
  (request) => {
    const settingsStore = useSettingsStore()
    const userStore = useUserStore()
    const expirationTime = storage.local.get('expiration-time') ?? ''
    if (new Date(expirationTime) < new Date()) {
      ElMessage.error('登录过期，请重新登录')
      storage.local.set('pollingNum', `0`)
      userStore.logout()
    }
    if (request.headers) {
      request.headers['Accept-Language'] = settingsStore.lang
      if (userStore.isLogin) {
        const token = storage.local.get('token')
        request.headers.Authorization = `Bearer ${token}`

        if (AxiosApi.OnOffGet()) {
          const refreshToken = storage.local.get('refresh_token')
          if (refreshToken && refreshToken !== 'undefined') {
            request.headers['x-Authorization'] = `Bearer ${refreshToken}`
          }
          // else {
          //   ElMessage.error('token失效，请重新登录')
          //   userStore.logout()
          // }
          // request.headers['x-Authorization'] = `Bearer ${refreshToken}`

          // request.headers['x-access-token'] = refreshToken
        }
      }
    }
    return request
  },
)

api.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()

    if (!userStore.isLogin && response.headers['access-token']) {
      storage.local.set('token', response.headers['access-token'])
      storage.local.set('refresh_token', response.headers['x-access-token'])
      storage.local.set('expiration-time', response.headers['x-access-token_expired-time'] !== undefined ? response.headers['x-access-token_expired-time'] : '')
      storage.local.set('pollingNum', `0`)
    }

    if (AxiosApi.OnOffGet() && response.headers['access-token']) {
      storage.local.set('token', response.headers['access-token'])
      storage.local.set('refresh_token', response.headers['x-access-token'])
      storage.local.set('expiration-time', response.headers['x-access-token_expired-time'] !== undefined ? response.headers['x-access-token_expired-time'] : '')
      AxiosApi.SwitchOnOff()
      storage.local.set('pollingNum', `0`)
    }

    if (response.headers['content-disposition']) {
      const fileName = response.headers['content-disposition'].split('filename=')[1]
      // console.log(fileName)
      storage.local.set('fileName', decodeURIComponent(fileName))
    }

    if (userStore.isLogin && response.data.statusCode === 401) {
      if (Number(pollingNum) <= 10) {
        pollingNum = Number(pollingNum) + 1
        storage.local.set('pollingNum', `${pollingNum}`)
      }
      else {
        ElMessage.error('获取TOKEN超时，请重新登录')
        storage.local.set('pollingNum', `0`)
        userStore.logout()
      }
      !(AxiosApi.OnOffGet()) ? AxiosApi.SwitchOnOff() : AxiosApi.OnOffGet()
      return api.request(response.config)
    }
    return Promise.resolve(response.data)
  },
  (error) => {
    let message = error.message
    if (message === 'Network Error') {
      message = '后端网络故障'
    }
    else if (message.includes('timeout')) {
      message = '接口请求超时'
    }
    else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`
    }
    else {
      // 其他错误处理
      message = error.response?.data?.error || '未知错误'
    }
    Message.error(message, {
      zIndex: 2000,
    })
    return Promise.reject(error)
  },
)

export default api
